<template>
  <div class="container">
    <xtx-select
      @update:modelValue="changeYear"
      width="100px"
      v-model="year"
      :options="yearOptions"
      placeholder="年"
    ></xtx-select>
    <xtx-select
      @update:modelValue="changeMonth"
      width="90px"
      v-model="month"
      :options="monthOptions"
      placeholder="月"
    ></xtx-select>
    <xtx-select
     @update:modelValue="changeDate"
      width="90px"
      v-model="date"
      :options="dateOptions"
      placeholder="日"
    ></xtx-select>
  </div>
</template>

<script>
import { onMounted, ref, watch } from 'vue'
import dayjs from 'dayjs'
export default {
  name: 'XtxDate',
  props: {
    modelValue: {
      type: String,
      default: ''
    }
  },
  setup (props, { emit }) {
    const year = ref('')
    const yearOptions = ref([])
    const month = ref('')
    const monthOptions = ref([])
    const date = ref('')
    const dateOptions = ref([])
    onMounted(() => {
      initYearAndMonthOptions()
      dateOptions.value = []
    })
    // 对父组件传递的值进行监听，然后拆分为页面展示所需要的数据格式
    watch(() => props.modelValue, () => {
      if (props.modelValue) {
        const arr = props.modelValue.split('-')
        year.value = arr[0]
        month.value = arr[1]
        date.value = arr[2]
        initDateOptions()
      } else {
        year.value = ''
        month.value = ''
        date.value = ''
      }
    }, { immediate: true })
    // 初始化年月选项数据
    const initYearAndMonthOptions = () => {
      const currYear = dayjs().year()
      for (let i = currYear; i >= 1949; i--) {
        yearOptions.value.push({ value: i.toString(), label: i + '年' })
      }
      for (let i = 1; i <= 12; i++) {
        monthOptions.value.push({ value: i > 10 ? i.toString() : '0' + i, label: i + '月' })
      }
    }
    // 初始化日选项数据
    const initDateOptions = () => {
      // 对日期数据进行清空后再次进行当月天数计算
      dateOptions.value = []
      const dateCount = dayjs().year(year.value).month(month.value).date(0).date()
      for (let i = 1; i <= dateCount; i++) {
        dateOptions.value.push({ value: i > 10 ? i.toString() : '0' + i, label: i + '日' })
      }
    }
    // 切换年份函数（reslut）是select子组件修改后的新值
    const changeYear = (result) => {
      year.value = result
      // 对绑定值置空
      month.value = ''
      date.value = ''
      // 将日期选项数据置空
      dateOptions.value = []
    }
    // 切换月份函数
    const changeMonth = (result) => {
      month.value = result
      // 对绑定值置空
      date.value = ''
      // 将日期选项数据置空
      initDateOptions()
    }
    // 切换日期函数
    const changeDate = (result) => {
      date.value = result
      emit('update:modelValue', `${year.value}-${month.value}-${date.value}`)
    }
    return { year, yearOptions, month, monthOptions, date, dateOptions, initYearAndMonthOptions, initDateOptions, changeYear, changeMonth, changeDate }
  }
}
</script>

<style lang="less" scoped>
.xtx-select~.xtx-select {
  margin-left: 10px;
}
</style>
